package com.llsydn.demo.guard;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.llsydn.hello.R;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2018/9/25 8:45
 */
public class GuardsAdapter extends BaseAdapter {
    private String[] names;
    private int[] icons;
    private Context context;
    private SharedPreferences sp;

    public GuardsAdapter(Context context, String[] names, int[] icons) {
        this.context = context;
        this.names = names;
        this.icons = icons;
        this.sp = context.getSharedPreferences("llsydn", Context.MODE_PRIVATE);
    }

    @Override
    public int getCount() {
        return names.length;
    }

    @Override
    public Object getItem(int position) {
        return names[position];
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //1.如果convertView为null，加载item的布局文件
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.item_guard, null);
        }
        //2.得到当前行需要更新的子view对象
        ImageView imageView = convertView.findViewById(R.id.iv_item_icon);
        TextView textView = convertView.findViewById(R.id.tv_item_name);
        //3.给视图设置数据
        imageView.setImageResource(icons[position]);
        textView.setText(names[position]);

        if (position == 0) {
            //从sp中读取保存的名称，如果存在显示
            String saveName = sp.getString("NAME", null);
            if (null != saveName) {
                textView.setText(saveName);
            }
        }
        //4.返回视图
        return convertView;
    }
}
